import {pathToRegexp, match, parse, compile} from "path-to-regexp";

export default function (jv) {
//an = action name 页面上 权限名称
    jv.an_version = 0;
//节流，防止多次请求。
    jv.an_ajaxed = false;
//收集页面所有的 v-an 值
    jv.get_ans = (vnode) => {
        var ret = [];
        vnode = vnode || jv.main;

        var directives = vnode.$vnode.data.directives;
        if (directives && directives[0].name == "an") {
            ret.push(directives[0].expression)
        }

        vnode.$children.forEach(it => {
            ret.pushAll(jv.get_ans(it))
        })
        return ret;
    }

    Object.defineProperty(jv.Vue.prototype, "has_an", {
        value(an) {
            if (!jv.ans) {
                return false;
            }
            var path = this.$route.path;
            var ans = jv.ans[path];
            if (!ans) return false;

            return ans.includes(an)
        }, enumerable: false
    });


//an = action name 页面上 权限名称
    jv.Vue.directive('an', {
        bind(el, binding, vnode) {
            if (!jv.an_ajaxed) {
                jv.an_ajaxed = true;

                jv.main.$http.post("/sys/get-ans").then(res => {
                    jv.ans = res.data; // map
                    jv.main.an_version++
                })
            }
            vnode.key = jv.main.an_version;


            var set_no = function () {
                el.classList.add("an-no");
            };

            var set_yes = function () {
                el.classList.remove("an-no");
            }

            if (!jv.ans) {
                return set_no()
            }

            var path = jv.main.$route.path;

            var ans_keys = Object.keys(jv.ans);
            var def_key = ans_keys.getLast(it => pathToRegexp(it).exec(path))
            if (!def_key) {
                return set_no()
            }

            var ref = (binding.arg || binding.expression).trim();
            var def = jv.ans[def_key]
            var isZheng = !ref.startsWith("!")
            if (!isZheng) {
                ref = ref.slice(1).trim();
            }
            if (def.includes(ref) == isZheng) {
                set_yes();
            } else {
                set_no();
            }
        }
    });
}